package com.yunbao.hujin.mychoosealbum;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yunbao.hujin.mychoosealbum.adapter.AdapterCameraImage;
import com.yunbao.hujin.mychoosealbum.adapter.AdapterShowListItem;
import com.yunbao.hujin.mychoosealbum.model.CameraImageBean;
import com.yunbao.hujin.mychoosealbum.utils.Const;
import com.yunbao.hujin.mychoosealbum.utils.GlideUtil;
import com.yunbao.hujin.mychoosealbum.utils.ZLog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 所有照片查看的界面
 */
public class ChooseImgAllActivity extends AppCompatActivity implements View.OnClickListener {

    private final static int SCAN_OK = 0x0001;
    private static final int CameraIntentRequest = 0;

    private RecyclerView gridAllPhoto;      //展示所有照片
    private LinearLayout showAllForList;    //分项展示的视图
    private ListView showList;              //分项展示的列表

    private ImageView showItem;
    private ImageView back;                 //返回
    private TextView title;                 //标题
    //    private TextView send;                  //发送按钮
    private TextView tvRight;               //发送按钮

    private List<String> allPath;           //手机中所有图片的路径集合
    private List<CameraImageBean> itemList;//手机中按父路径分类的图片路径集合
    //展示大图用到
    public List<String> gridList;           //RecyclerView的GridView显示图片的集合

    private HashMap<String, List<String>> mGroupMap;

    private int counts;                 //选择图片张数的上限
    private boolean isshowItem = false;//是否展开分项列表，默认不展开
    private String filepath;            //调用相机拍照文件的保存路径

    private ProgressDialog mProgressDialog;
    private AdapterCameraImage adapter;      //显示所有图片的RecyclerView的适配器
    private AdapterShowListItem listAdapter; //图片排列方式adapter


    public static ChooseImgAllActivity instance;  //展示大图用到

    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case SCAN_OK:
                    mProgressDialog.dismiss();
                    sortList();
                    showListSetAdapter();
                    gridListSetAdapter();
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chose_image_all);
        instance = this;
        initView();
        initData();
        bindView();
    }

    private void initView() {
        gridAllPhoto = findViewById(R.id.camera_img_allphoto);
        showAllForList = findViewById(R.id.camera_img_showallforlist);
        showList = findViewById(R.id.camera_img_showlist);
        back = findViewById(R.id.camera_img_back);

        showItem = findViewById(R.id.camera_img_showitem);//点击可以展开图片的分类列表
//        send = findViewById(R.id.camera_right);
        title = findViewById(R.id.camera_img_title);
        tvRight = findViewById(R.id.camera_right);
    }

    //监听
    private void bindView() {
        back.setOnClickListener(this);
        showItem.setOnClickListener(this);  //点击展开分类
        showListSetOnItemClickListener();
//        gridAllPhotoSetOnItemClickListener();
        tvRight.setOnClickListener(this);
    }

    private void initData() {
        buildMkDir();
        allPath = new ArrayList<>();
        itemList = new ArrayList<>();
        gridList = new ArrayList<>();
        mGroupMap = new HashMap<>();

        counts = getIntent().getIntExtra(Const.THE_NUM_OF_PHOTO, 0);
        if (counts == 1) {
            tvRight.setText("确认");
        }
        getImages();
    }

    /**
     * 文件夹不存在就创建
     */
    private void buildMkDir() {
        File pfile = new File(Const.cameraImageParentPath);
        if (!pfile.exists()) {
            pfile.mkdirs(); //创建文件夹
        }
    }

    //将集合倒序排列
    private void sortList() {
        List<String> temp = new ArrayList<>();
        for (int i = allPath.size() - 1; i > 0; i--) {
            temp.add(allPath.get(i));
        }
        allPath.clear();
        allPath.addAll(temp);
    }

    //分项展示设置适配器
    private void showListSetAdapter() {
        CameraImageBean bean = new CameraImageBean();
        bean.setFolderName("所有照片");
        bean.setImageCounts(allPath.size());
        if (allPath.size() > 0) {
            bean.setTopImagePath(allPath.get(0));
        } else {
            bean.setTopImagePath("");
        }
        itemList.add(bean);
        itemList.addAll(subGroupOfImage(mGroupMap));
        listAdapter = new AdapterShowListItem(this, itemList);
        showList.setAdapter(listAdapter);
    }

    /**
     * 组装手机中按父路径分类的图片路径集合的数据源
     */
    private List<CameraImageBean> subGroupOfImage(HashMap<String, List<String>> mGroupMap) {
        List<CameraImageBean> list = new ArrayList<>();

        CameraImageBean bean = new CameraImageBean();
        bean.setFolderName("所有照片");
        bean.setImageCounts(allPath.size());
        if (allPath.size() > 0) {
            bean.setTopImagePath(allPath.get(0));
        } else {
            bean.setTopImagePath("");
        }
        if (mGroupMap.size() == 0) {
            return list;
        }

        Iterator<Map.Entry<String, List<String>>> iterator = mGroupMap.entrySet().iterator();

        while (iterator.hasNext()) {
            Map.Entry<String, List<String>> entry = iterator.next();
            CameraImageBean imageBean = new CameraImageBean();
            String key = entry.getKey();
            List<String> value = entry.getValue();

            imageBean.setFolderName(key);
            imageBean.setImageCounts(value.size());
            imageBean.setTopImagePath(value.get(0));

            list.add(imageBean);
        }
        return list;
    }

    //所有照片设置适配器
    private void gridListSetAdapter() {
        gridList.add(Const.PHOTO);
        gridList.addAll(allPath);
        adapter = new AdapterCameraImage(this, gridList, counts);

        GridLayoutManager manager = new GridLayoutManager(this, 3);
        gridAllPhoto.setLayoutManager(manager);
        gridAllPhoto.setAdapter(adapter);

        gridAllPhotoSetOnItemClickListener();
    }


    /**
     * 获取数据
     * 通过ContentProvider扫描手机中的图片
     */
    private void getImages() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "没有内存设置", Toast.LENGTH_SHORT).show();
            return;
        }
        mProgressDialog = ProgressDialog.show(this, null, "正在加载...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ZLog.e(String.valueOf(mImageUri));

                ContentResolver resolver = ChooseImgAllActivity.this.getContentResolver();
                Cursor cursor = resolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or " +
                                MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED);

                while (cursor.moveToNext()) {
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
//                    ZLog.i(path);       ///storage/emulated/0/BigNoxHD/cache/***.png--------/storage/emulated/0/com.yunbao.financial/nfile/html/images/**.png

                    allPath.add(path);

                    String parentName = new File(path).getParentFile().getName();

//                    ZLog.i(parentName);     //cache--images

                    if (!mGroupMap.containsKey(parentName)) {
                        List<String> childList = new ArrayList<>();
                        childList.add(path);
                        mGroupMap.put(parentName, childList);

                    } else {
                        mGroupMap.get(parentName).add(path);
                    }
                }

                cursor.close();
                mHandler.sendEmptyMessage(SCAN_OK);
            }
        }).start();
    }

    /*****************-------点击事件------**************************/
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.camera_img_back:          //标题栏返回按钮
                finish();
                break;
            case R.id.camera_img_showitem:      //标题栏照片分类按钮
                if (!isshowItem) {
                    showItem.setImageResource(R.mipmap.liaotian_xiangshang);
                    showAllForList.setVisibility(View.VISIBLE);
                } else {
                    showItem.setImageResource(R.mipmap.liaotian_xiangxia);
                    showAllForList.setVisibility(View.GONE);
                }
                isshowItem = !isshowItem;
                break;
            case R.id.camera_right:         //标题栏确认、完成按钮
                if (adapter != null) {
                    ArrayList<String> selectList = (ArrayList<String>) adapter.getSelectList();
                    Intent intent = new Intent();
                    intent.putStringArrayListExtra(Const.SELECT_RESULT_INTENT, selectList);
                    setResult(Const.SELECT_RESULT_CODE, intent);
                }
                finish();
                break;
        }
    }

    //RecyclerView 条目点击事件
    private void gridAllPhotoSetOnItemClickListener() {
        if (adapter != null) {
            adapter.setOnGridItemClick(new AdapterCameraImage.OnGridItemClick() {
                @Override
                public void onItemClick(int position) {
                    String listPath = gridList.get(position);
                    if (listPath.equals(Const.PHOTO)) {
                        //照相机的点击事件，调用本地相机
                        jumpToCamera();
                    } else {
                        //图片查看轮播
//                        Intent intent = new Intent(ChooseImgAllActivity.this, ChooseImgShowActivity.class);
                        Intent intent = new Intent(ChooseImgAllActivity.this, ChooseImgShow2Activity.class);
                        //由于Intent传值对大小有限制，如果手机图片很多的情况下此值无法传递，所以通过静态调用
                        //intent.putStringArrayListExtra(Const.GOTO_FOR_SHOW_IMG, (ArrayList<String>) gridList);
                        intent.putExtra(Const.GOTO_FOR_SHOW_IMG_POSITION, position);
                        startActivity(intent);
                    }
                }
            });
        }
    }

    // 分项展示的点击事件
    private void showListSetOnItemClickListener() {
        //ListView条目点击事件
        showList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CameraImageBean bean = (CameraImageBean) parent.getAdapter().getItem(position);
                String parentPath = bean.getFolderName();
                if (parentPath.equals("所有照片")) {
                    gridList.clear();
                    gridList.add(Const.PHOTO);
                    gridList.addAll(allPath);

                } else {
                    gridList.clear();
                    List<String> tempx = mGroupMap.get(itemList.get(position).getFolderName());
                    List<String> temp = new ArrayList<>();
                    for (int i = tempx.size() - 1; i >= 0; i--) {
                        temp.add(tempx.get(i));
                    }
                    gridList.addAll(temp);
                }

                title.setText(parentPath);
                adapter.notifyDataSetChanged();
                showAllForList.setVisibility(View.GONE);
                showItem.setImageResource(R.mipmap.liaotian_xiangxia);
                isshowItem = false;
            }
        });
    }


    //跳转相机
    private void jumpToCamera() {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);  //跳转到调用系统相机
        intent.addCategory(Intent.CATEGORY_DEFAULT);

        //如果在Android7.0以上,使用FileProvider获取Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            // 或 用 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
            Uri uri = FileProvider.getUriForFile(this, "com.yunbao.mychoosealbum", initTempFile());
            ZLog.e("7.0的-"+String.valueOf(uri));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        } else {
            // 把文件地址转换成Uri格式
            //否则使用Uri.fromFile(file)方法获取Uri
            Uri uri = Uri.fromFile(initTempFile());
            ZLog.e("7.0以下-"+String.valueOf(uri));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//Android7.0不能使用这段代码
        }
        startActivityForResult(intent, CameraIntentRequest);
    }


    //创建临时文件
    private File initTempFile() {
//        filepath = new File(Environment.getExternalStorageDirectory().getPath(), System.currentTimeMillis() + ".jpg");
        filepath = Const.cameraImageParentPath + "img" + System.currentTimeMillis() + ".jpg";
        File file = new File(filepath);
        return file;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //拍完照片后的返回
        if (requestCode == CameraIntentRequest && resultCode == RESULT_OK) {
            //用相机返回的照片（去调用剪裁）也需要对Uri进行处理（Android7.0）
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(this, "com.yunbao.mychoosealbum", new File(filepath));
            } else {
                uri = Uri.fromFile(new File(filepath));
            }
            intent.setData(uri);
            sendBroadcast(intent);  //发送广播

            Intent backintent = new Intent();
            backintent.putExtra(Const.PTO_RESULT_INTENT, filepath);//拍照选中的照片
            setResult(Const.PTO_RESULT_CODE, backintent);
            finish();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
        gridAllPhoto = null;
        GlideUtil.clearGlideMemory(this);
        setContentView(R.layout.view_null);
    }


}
